package service;
import java.util.List;
import entity.user;
import dao.user_dao;
public class login_service {
	private user_dao d_user=new user_dao();
	public user login(user u) {
		String username=u.getUser_name();
		String password=u.getPassword();
		List<user>res=d_user.select("select * from user where user_name=\""+username+"\"");
		if (res.isEmpty()){
			u.setType(-1);
			return u;
		}
		String true_password=res.get(0).getPassword();
		if(true_password.equals(password)==false){
			u.setType(-2);
			return u;
		}
		u.setType(res.get(0).getType());
		return u;
	}
	public boolean sign(user u) {
		String username=u.getUser_name();
		List<user>res=d_user.select("select * from user where user_name=\""+username+"\"");
		if (!res.isEmpty()){
			return false;
		}
		String password=u.getPassword();
		String security_answer=u.getSecurity_answer();
		String security_question=u.getSecurity_question();
		String sql=String.format("insert into user values(\"%s\",\"%s\",1,\"%s\",\"%s\")", username, password, security_question,security_answer);
		d_user.add(sql);
		return true;
	}
	public user find(user u) {
		String username=u.getUser_name();
		List<user>res=d_user.select("select * from user where user_name=\""+username+"\"");
		if (res.isEmpty()){
			u.setType(-1);
			return u;
		}
		return res.get(0);
	}
	public boolean answer_correct(user u) {
		String username=u.getUser_name();
		String security_answer=u.getSecurity_answer();
		String sql=String.format("select * from user where user_name=\"%s\" and security_answer=\"%s\"", username,security_answer);
		List<user>res=d_user.select(sql);
		if (res.isEmpty()){
			return false;
		}
		return true;
	}
	public void forget(user u) {
		String username=u.getUser_name();
		String password=u.getPassword();
		String sql=String.format("update user set password=\"%s\" where user_name=\"%s\"", password,username);
		d_user.change(sql);
	}
}
